from django.db.models import Q

from shop import models, serializer
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from django.core.files.storage import default_storage
from rest_framework.pagination import PageNumberPagination
from django.core.cache import cache
from drf_haystack.viewsets import HaystackViewSet

from utils.redis import redistool


# Create your views here.

class nav(APIView):
    def get(self, resquest):
        if cache.get('nav'):
            return Response({"msg": "ok", "code": 200, "result": cache.get('nav')})
        else:
            position = resquest.query_params.get('position')
            list = models.nav.objects.filter(postion=position, isdel=False).values()
            # 考虑空值防止缓存穿透
            if not list:
                cache.set('nav', "", 60 * 2)
                return Response({"msg": "ok", "code": 200, "result": cache.get('nav')})
            else:
                cache.set('nav', list, 60 * 60)
                return Response({"msg": "ok", "code": 200, "result": cache.get('nav')})


class upload(APIView):
    def post(self, request):
        file = request.data.get('file')
        # 校验格式
        allow = ["image/png", "image/jpg", "image/jpeg"]
        if file.content_type not in allow:
            return Response({"msg": "图片格式不支持"})
        if file.size > 3 * 1024 * 1024:
            return Response({"msg": "文件不支持超过3MB"})

        result = default_storage.save("upload/" + file.name, file)
        # 获取路径
        url = default_storage.url(result)
        return Response({'msg': 'ok', 'url': url})


class category(APIView):
    def get(self, request):
        if cache.get('categroy'):
            return Response({"msg": "ok", "code": 200, "categroylist": cache.get('categroy')})
        else:
            list = models.categroy.objects.filter(isdel=False, parent=None)
            ser_data = serializer.categroy(list, many=True)
            result = ser_data.data
            for item in result:
                item['children'] = item['children'][:3]
            if not list:
                cache.set('categroy', '', 60 * 2)
                return Response({"msg": "没有查询到数据", "code": 200})
            else:
                cache.set('categroy', result, 60 * 60 * 24)
                return Response({"msg": "ok", "code": 200, "categroylist": cache.get('categroy')})


class categoryinfo(APIView):
    def get(self, request):
        targetid = request.query_params.get('id')
        if not targetid:
            return Response("id不能为空")
        if cache.get('categroyinfo'):
            return Response({"msg": "ok", "code": 200, "categroyinfo": cache.get('categroyinfo')})
        else:
            info = models.categroy.objects.filter(parent=targetid, isdel=False)
            ser_data = serializer.categroy(info, many=True)
            result = ser_data.data
            if not info:
                cache.set('categroyinfo', '', 60 * 2)
                return Response({"msg": "没有查询到数据", "code": 200})
            else:
                cache.set('categroyinfo', result, 60 * 2)
                return Response({"msg": "ok", "code": 200, "categroyinfo": cache.get('categroyinfo')})


class direction(APIView):
    def get(self, request):
        result = models.categroy.objects.filter(parent=None, isdel=False)
        data = serializer.categroywithoutchild(result, many=True).data
        return Response({"msg": "成功", "code": 200, "data": data})


class cate(APIView):
    def get(self, request):
        direction = request.query_params.get("direction", "0")
        if not direction:
            # __isnull判断是不是null
            result = models.categroy.objects.filter(parent__isnull=False, isdel=False)
            data = serializer.categroywithoutchild(result, many=True).data
            return Response({"msg": "成功", "code": 200, "data": data})
        else:
            result = models.categroy.objects.filter(parent=direction, isdel=False)
            data = serializer.categroywithoutchild(result, many=True).data
            return Response({"msg": "成功", "code": 200, "data": data})


class coursepagination(PageNumberPagination):
    page_size = 3
    page_query_param = "size"


class course(ListAPIView):
    queryset = models.course.objects.all()
    serializer_class = serializer.course
    pagination_class = coursepagination

    # ListAPIView 对应的是get_queryset

    def get_queryset(self):
        # 默认的筛选答案
        query = Q()
        # 获取参数
        nav = self.request.query_params.get("nav", "")
        cate = self.request.query_params.get("cate", "")
        direction = self.request.query_params.get("direction", "")
        ordering = self.request.query_params.get("ordering", "")
        # query条件的拼接
        if nav:
            query &= Q(nav=nav)
        if cate:
            query &= Q(category=cate)
        if direction and not cate:
            # 第一次用到values_list(xx,)可以获取里面所有的值flat扁平化处理
            child = models.categroy.objects.filter(parent=direction, isdel=False).values_list("id", flat=True)
            query &= Q(category__in=child)
        if ordering:
            return self.queryset.filter(query).order_by(ordering)
        else:
            return self.queryset.filter(query)


class coursedetail(APIView):
    def get(self, request):
        id = request.query_params.get('id', "")
        if not id:
            return Response({"msg": "id不能为空"})
        info = models.course.objects.filter(id=id).first()
        serinfo = serializer.coursedetail(info).data
        if not info:
            return Response({"msg": "无效的id"})
        return Response({"msg": "成功", "code": 200, "info": serinfo})


class chapter(APIView):
    def get(self, request):
        id = request.query_params.get('id', "")
        if not id:
            return Response({"msg": "id不能为空"})
        list = models.chapter.objects.filter(course=id)
        serlist = serializer.chapter(list, many=True).data
        total = 0
        for item in serlist:
            # target = models.node.objects.filter(chapter=item['id'])
            # item['node'] = serializer.node(target, many=True).data
            for subitem in item['node']:
                total += subitem['priod']
            item['totaltime'] = total
        return Response({"msg": "成功", "code": 200, "data": serlist})


class courseSearch(HaystackViewSet):
    index_models = [models.course]  # orm的模型
    serializer_class = serializer.CourseSearchSerializer  # 索引序列化器
    # 分页
    pagination_class = coursepagination

    def list(self, request, *args, **kwargs):
        # 重写list方法  获取到搜索的参数
        word = request.query_params.get("text", "")
        if word:
            # 将关键词存储到redis中
            redistool.set_word(word)
        return super().list(request, *args, **kwargs)


class hotWord(APIView):
    def get(self, request):
        # 获取redis中存储的搜索关键词
        wordlist = redistool.get_word()
        return Response({"msg": "ok", "data": wordlist})
